package com.br.socket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.UUID;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.br.command.BaseCommand;
import com.br.command.CommandFactory;
import com.br.command.impl.Desconectar;
import com.br.entities.Player;

public final class ConnectionWS extends MessageInbound {
	
	//instancia do jogador
	private Player player;
	
	//id unico da conexao
	private UUID id;
	
	private Logger logger = Logger.getLogger(this.getClass());
	
    protected void onOpen(WsOutbound outbound) {
    	//gera um id ao abrir a conexao
    	id = UUID.randomUUID();
    	
        // Adiciona essa nova conexao lista de conexoes
        GameSocket.getConnections().add(this);
        
        logger.debug("Conexao aberta...");
    }
 
    protected void onClose(int status) {
    	new Desconectar().process(this, null);
    	super.onClose(status);
    }
    
    protected void onBinaryMessage(ByteBuffer arg0) throws IOException {
        throw new RuntimeException("Metodo nao aceito");
    }
 
    protected void onTextMessage(CharBuffer msg) throws IOException {
    	
    	String strMsg = msg.toString();
    	
    	logger.debug("onTextMessage: " + strMsg);
    	
    	JSONObject jsonMsg = new JSONObject(strMsg);
    	
		//tipo da mensagem
        String tipo = jsonMsg.getString("tipo");
        
        //cria o comando para o tipo
        BaseCommand command = CommandFactory.getInstancia().create(tipo);
        
       //processa a mensagem
        if(command!=null){
        	command.process(this, jsonMsg);
        }
        
    }

    public void sendMessage(String message) throws IOException{
    	logger.debug("sendMessage: " + message);
    	this.getWsOutbound().writeTextMessage( CharBuffer.wrap(message)  ) ;
    }
    
	public Player getPlayer() {
		return player;
	}

	public void setPlayer(Player player) {
		this.player = player;
	}

	public UUID getId() {
		return id;
	}

	public void setId(UUID id) {
		this.id = id;
	}
 
}


